<?php
/**
 * GeoContexter
 * @link http://code.google.com/p/geocontexter/
 * @package GeoContexter
 */

/**
 * spatial search for records
 *
   USAGE:
   <pre>
   // tested with postgis 1.4.0
   //

   $RecordGet = $this->CoreModel('RecordGet');

   $params  = array('id_record'        => bigint);

   $result  = $RecordGet->run( $params );

   if ($result instanceof \Core\Library\Exception) {
       return $this->error( $result->getMessage(), __file__, __line__);
   } else {
       $this->view->result = $result;
   }

   </pre>
 * @package GeoContexter
 * @subpackage Module_Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev: 896 $ / $LastChangedDate: 2011-08-14 15:30:16 +0200 (So, 14 Aug 2011) $ / $LastChangedBy: armand.turpel@gmail.com $
 */

namespace Geocontexter\Model;

use Core\Model\AbstractModel;
use Core\Model\InterfaceModel;

class RecordGet extends    AbstractModel
                implements InterfaceModel
{
    /**
     * @param array $params
     */
    public function run( $params )
    {
        try {

            $this->validate_params($params);

      // check on preferred lists only
      //
      $_default_display = null;
      if (isset($params['default_display'])) {
        $_default_display = $params['default_display'];
      }

            $_precision = 8;
            if (isset($params['precision'])) {
                $_precision = (int) $params['precision'];
            }

            $sql = 'SELECT rec.*,
                           hstore_to_json(rec.attribute_value) AS attribute_value,
                           geocontexter.ST_AsOpenLayersGeometry('.$this->sql_geom_column.', '.$_precision.') AS ol_geometry,
                           it.title,
                           it.id_item

                    FROM       geocontexter.gc_record AS rec

                    INNER JOIN geocontexter.gc_record_geometry AS recg
                            ON recg.id_record = rec.id_record

                    INNER JOIN geocontexter.gc_item AS it
                            ON rec.id_item = it.id_item

                    WHERE  rec.id_record = ' . $params['id_record'];


            // json decode of attribute_values
            //

            $result = $this->query($sql);

            if (!isset($result[0])) {
                  throw new \Exception('id_record dosent exists: ' . $params['id_record']);
            }

            $_result = $result[0];


      // json decode of content in row "attribute_values"
      //

      $AttributeJsonDecode = $this->CoreModel('AttributeJsonDecode');

      $_result['attribute_value'] = $AttributeJsonDecode->decode( $_result['attribute_value'], $_result['id_attribute_group'], $_default_display );

      return $_result;

      } catch(\Exception $e) {
        throw $e;
      }
    }

    /**
     * count total rows without limit
     *
     * @return int total num rows
     * @todo optimize the query
     */


    /**
     * set and validate parameters
     *
     *
     * @param array $params
     */
    private function validate_params( & $params )
    {
        if (!isset($params['id_record'])) {
            throw new \Exception('id_record field isnt defined');
        }

        $val_digits = new \Zend\Validator\Digits();

        if (false === $val_digits->isValid($params['id_record'])) {
            throw new \Exception('id_record isnt from type bigint');
        }

        if (isset($params['geometry_column'])) {
            if (false === in_array($params['geometry_column'], array('point', 'linestring', 'polygon'))) {
                throw new \Exception('geometry_type must be one of string: "point", "linestring", "polygon"');
            } else {
                $this->sql_geom_column = 'recg.geom_' . $params['geometry_column'];
            }
        } else {
            $this->sql_geom_column = 'ST_ConvexHull(ST_Collect(recg.geom_point, recg.geom_linestring, recg.geom_polygon))';
        }
    }
}
